<template>
  <div class="admin-dashboard-container">
    <!-- 1. 顶部数据概览 -->
    <el-row :gutter="20" class="panel-group">
      <el-col :lg="6" :md="12" :sm="12" :xs="24">
        <el-card shadow="hover" class="metric-card bg-blue">
          <div class="metric-content">
            <el-icon class="metric-icon"><User /></el-icon>
            <div class="metric-details">
              <div class="metric-title">在住老人总数</div>
              <div class="metric-value">{{ metrics.residentCount }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :lg="6" :md="12" :sm="12" :xs="24">
        <el-card shadow="hover" class="metric-card bg-red">
          <div class="metric-content">
            <el-icon class="metric-icon"><Warning /></el-icon>
            <div class="metric-details">
              <div class="metric-title">今日健康预警</div>
              <div class="metric-value">{{ metrics.healthAlertsToday }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :lg="6" :md="12" :sm="12" :xs="24">
        <el-card shadow="hover" class="metric-card bg-orange">
          <div class="metric-content">
            <el-icon class="metric-icon"><Tickets /></el-icon>
            <div class="metric-details">
              <div class="metric-title">待处理事务</div>
              <div class="metric-value">{{ metrics.pendingTasks }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :lg="6" :md="12" :sm="12" :xs="24">
        <el-card shadow="hover" class="metric-card bg-green">
          <div class="metric-content">
            <el-icon class="metric-icon"><OfficeBuilding /></el-icon>
            <div class="metric-details">
              <div class="metric-title">空闲床位数</div>
              <div class="metric-value">{{ metrics.vacantBeds }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 2. 中部核心区域 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <!-- 左侧：待办事项 & 趋势图 -->
      <el-col :span="16">
        <!-- 待办事项 -->
        <el-card shadow="never">
          <template #header>
            <div class="card-header">
              <span>近期待办事项</span>
              <el-button class="button" text @click="handleAction('查看全部待办')">查看全部</el-button>
            </div>
          </template>
          <el-tabs v-model="activeTab" class="task-tabs">
            <el-tab-pane :label="`待审核预约 (${pendingAppointments.length})`" name="appointment">
              <el-table v-loading="loading.tasks" :data="pendingAppointments" stripe style="width: 100%" height="220px" :empty-text="loading.tasks ? '加载中...' : '暂无待审核预约'">
                <el-table-column prop="applicantName" label="申请人" width="120" />
                <el-table-column prop="relatedElderlyName" label="探访老人" width="120" />
                <el-table-column prop="taskTime" label="预约时间" :formatter="formatDateTime" />
                <el-table-column label="操作" width="100">
                  <template #default="scope">
                    <el-button type="primary" link @click="handleAction(`处理预约 ${scope.row.applicantName}`)">处理</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
            <el-tab-pane :label="`待审批申请 (${pendingApplications.length})`" name="application">
              <el-table v-loading="loading.tasks" :data="pendingApplications" stripe style="width: 100%" height="220px" :empty-text="loading.tasks ? '加载中...' : '暂无待审批申请'">
                <el-table-column prop="taskType" label="申请类型" width="120" />
                <el-table-column prop="applicantName" label="申请人" />
                <el-table-column prop="taskTime" label="申请日期" :formatter="formatDate" />
                <el-table-column label="操作" width="100">
                   <template #default="scope">
                    <el-button type="primary" link @click="handleAction(`审批申请 ${scope.row.applicantName}`)">审批</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
            <el-tab-pane :label="`最新反馈 (${latestFeedback.length})`" name="feedback">
              <el-table v-loading="loading.tasks" :data="latestFeedback" stripe style="width: 100%" height="220px" :empty-text="loading.tasks ? '加载中...' : '暂无最新反馈'">
                <el-table-column prop="user" label="反馈人" width="120" />
                <el-table-column prop="content" label="内容摘要" show-overflow-tooltip />
                <el-table-column prop="status" label="状态" width="100">
                  <template #default="scope">
                    <el-tag :type="scope.row.status === '待处理' ? 'warning' : 'info'" size="small">{{ scope.row.status }}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="100">
                   <template #default="scope">
                    <el-button type="primary" link @click="handleAction(`查看反馈 ${scope.row.user}`)">查看</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </el-card>

        <!-- 趋势图 -->
        <el-card shadow="never" style="margin-top: 20px;">
          <template #header>
            <div class="card-header">
              <span>入住与床位占用率趋势 (近30天)</span>
            </div>
          </template>
          <div ref="trendsChart" v-loading="loading.chart" style="height: 300px;"></div>
        </el-card>
      </el-col>
      
      <!-- 右侧：健康预警 & 快捷入口 -->
      <el-col :span="8">
        <!-- 健康预警 -->
        <el-card shadow="never" v-loading="loading.alerts">
          <template #header>
            <div class="card-header">
              <span>实时健康预警</span>
              <el-icon color="#F56C6C"><WarningFilled /></el-icon>
            </div>
          </template>
           <el-empty v-if="healthAlerts.length === 0 && !loading.alerts" description="今日暂无健康预警" />
          <el-timeline v-else class="warning-timeline">
            <el-timeline-item
              v-for="alert in healthAlerts"
              :key="alert.id"
              :timestamp="formatRelativeTime(alert.recordTime)"
              type="danger"
              hollow
            >
              <strong>[{{ alert.alertType }}]</strong> {{ alert.elderlyName }}: {{ alert.description }}
            </el-timeline-item>
          </el-timeline>
        </el-card>

        <!-- 快捷入口 -->
        <el-card shadow="never" style="margin-top: 20px;">
          <template #header>
            <div class="card-header">
              <span>快捷入口</span>
            </div>
          </template>
          <div class="quick-access">
              <div class="access-item" @click="handleAction('跳转到老人档案')">
                  <el-icon class="access-icon" color="#3b82f6"><Avatar /></el-icon>
                  <span>老人档案</span>
              </div>
              <div class="access-item" @click="handleAction('跳转到床位管理')">
                  <el-icon class="access-icon" color="#16a34a"><OfficeBuilding /></el-icon>
                  <span>床位管理</span>
              </div>
              <div class="access-item" @click="handleAction('跳转到账单生成')">
                  <el-icon class="access-icon" color="#f97316"><Money /></el-icon>
                  <span>账单生成</span>
              </div>
              <div class="access-item" @click="handleAction('跳转到权限分配')">
                  <el-icon class="access-icon" color="#8b5cf6"><SetUp /></el-icon>
                  <span>权限分配</span>
              </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, onBeforeUnmount } from 'vue';
import * as echarts from 'echarts';
import {
  User, Warning, Tickets, OfficeBuilding, SetUp, Avatar, Money, WarningFilled
} from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import {
  getDashboardMetrics,
  getPendingAppointments,
  getPendingApplications,
  getLatestFeedback,
  getRealtimeHealthAlerts,
  getCheckInTrends
} from '@/api/dashboard';

// --- 响应式状态 ---
const activeTab = ref('appointment');
const trendsChart = ref(null);
let myChart = null;

const loading = reactive({
  metrics: true,
  tasks: true,
  alerts: true,
  chart: true,
});

const metrics = ref({
  residentCount: 0,
  healthAlertsToday: 0,
  pendingTasks: 0,
  vacantBeds: 0,
});

const pendingAppointments = ref([]);
const pendingApplications = ref([]);
const latestFeedback = ref([]);
const healthAlerts = ref([]);

// --- 辅助方法 ---
const handleAction = (actionName) => {
  // 这里可以换成路由跳转
  ElMessage.success(`执行操作：${actionName}`);
};

const formatDateTime = (row, column, cellValue) => {
  if (!cellValue) return '';
  const date = new Date(cellValue);
  return date.toLocaleString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' });
};

const formatDate = (row, column, cellValue) => {
    if (!cellValue) return '';
    const date = new Date(cellValue);
    return date.toLocaleDateString('zh-CN');
}

const formatRelativeTime = (timeStr) => {
  if (!timeStr) return '';
  const now = new Date();
  const past = new Date(timeStr);
  const diffInSeconds = Math.floor((now - past) / 1000);

  const minutes = Math.floor(diffInSeconds / 60);
  if (minutes < 1) return '刚刚';
  if (minutes < 60) return `${minutes}分钟前`;

  const hours = Math.floor(minutes / 60);
  if (hours < 24) return `${hours}小时前`;
  
  const days = Math.floor(hours / 24);
  return `${days}天前`;
};

// --- ECharts ---
const initTrendsChart = (chartData) => {
  if (!trendsChart.value) return;
  myChart = echarts.init(trendsChart.value);

  const option = {
    tooltip: { trigger: 'axis', axisPointer: { type: 'cross', crossStyle: { color: '#999' } } },
    legend: { data: ['新入住人数', '床位占用率'], textStyle: { color: '#606266' } },
    grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
    xAxis: [{ type: 'category', data: chartData.dateAxis || [], axisPointer: { type: 'shadow' } }],
    yAxis: [
      { type: 'value', name: '人数', min: 0, axisLabel: { formatter: '{value} 人' } },
      { type: 'value', name: '占用率', min: 0, max: 100, axisLabel: { formatter: '{value} %' } }
    ],
    series: [
      { name: '新入住人数', type: 'bar', barWidth: '20%', tooltip: { valueFormatter: (value) => value + ' 人' }, data: chartData.newCheckIns || [] },
      { name: '床位占用率', type: 'line', yAxisIndex: 1, smooth: true, tooltip: { valueFormatter: (value) => value.toFixed(2) + ' %' }, data: chartData.bedOccupancyRates || [] }
    ]
  };
  myChart.setOption(option);
};

const handleResize = () => {
  if (myChart) {
    myChart.resize();
  }
};

// --- 数据获取 ---
const fetchData = async () => {
  // 并行获取所有数据
  try {
    loading.metrics = true;
    loading.tasks = true;
    loading.alerts = true;
    loading.chart = true;
    
    const [metricsData, appointments, applications, feedback, alerts, trends] = await Promise.all([
      getDashboardMetrics(),
      getPendingAppointments(),
      getPendingApplications(),
      getLatestFeedback(),
      getRealtimeHealthAlerts(),
      getCheckInTrends()
    ]);
    
    metrics.value = metricsData;
    pendingAppointments.value = appointments;
    pendingApplications.value = applications;
    latestFeedback.value = feedback;
    healthAlerts.value = alerts;
    
    // 等待DOM更新后初始化图表
    await nextTick();
    initTrendsChart(trends);

  } catch (error) {
    console.error("获取仪表盘数据失败:", error);
    ElMessage.error("数据加载失败，请稍后重试！");
  } finally {
    loading.metrics = false;
    loading.tasks = false;
    loading.alerts = false;
    loading.chart = false;
  }
};


// --- 生命周期钩子 ---
onMounted(() => {
  fetchData();
  window.addEventListener('resize', handleResize);
});

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize);
  if (myChart) {
    myChart.dispose();
    myChart = null;
  }
});
</script>

<style scoped>
/* 样式与原文件保持一致，无需修改 */
.admin-dashboard-container {
  width: 99%;
  padding: 20px;
  background-color: #f0f2f5;
  min-height: 100vh;
}

.panel-group .metric-card {
  color: #fff;
  border: none;
  cursor: pointer;
  transition: all 0.3s ease-out;
}
.panel-group .metric-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.metric-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.metric-icon {
  font-size: 50px;
  opacity: 0.8;
}

.metric-details {
  text-align: right;
}

.metric-title {
  font-size: 14px;
  font-weight: 300;
  margin-bottom: 8px;
}

.metric-value {
  font-size: 26px;
  font-weight: bold;
}

.bg-blue { background: linear-gradient(to right, #409eff, #79bbff); }
.bg-red { background: linear-gradient(to right, #f56c6c, #f89898); }
.bg-orange { background: linear-gradient(to right, #e6a23c, #eebe77); }
.bg-green { background: linear-gradient(to right, #67c23a, #95d475); }


.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  font-weight: bold;
}

.el-card {
  border-radius: 8px;
  border: none;
}

.task-tabs .el-tabs__header {
  margin-bottom: 0;
}

.warning-timeline {
  padding-left: 10px;
}
.warning-timeline .el-timeline-item__timestamp {
  font-size: 12px;
}
.warning-timeline strong {
  color: #c0392b;
}

.quick-access {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
  text-align: center;
}

.access-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 15px 0;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease-in-out;
}
.access-item:hover {
  background-color: #f5f7fa;
  transform: scale(1.05);
}

.access-icon {
  font-size: 32px;
  margin-bottom: 10px;
}

.access-item span {
  font-size: 14px;
  color: #606266;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .panel-group .el-col {
    margin-bottom: 20px;
  }
}
</style>